<?php defined('SYSPATH') or die('No direct script access.');
                          
class Order_Controller extends Template_Controller 
{
	public $template = 'layout/order';
	
	public function __construct()
	{
		parent::__construct();
		
		if(!cookie::get('userid'))
		{
			url::redirect('cart/signin/'.str_replace('/', '_', Router::$current_uri), 301);
			exit;
		}
		
		$this->db = new Database();
		
		$this->session = new Session();
		$this->cart = $this->session->get('cart');

		$this->template->menu = '';
		$this->template->content = '';
		$this->template->leftmenu = $this->db->query('SELECT * FROM product_categories WHERE left_id>1 AND right_id <(SELECT right_id FROM product_categories WHERE id=1) AND layer_id<=2 ORDER BY left_id');
	}
		
	public function create($type)
	{
		if(count($this->cart['items']) > 0)
		{
			$discount = Config::item('bookstore.discount');
			
			$model = new Country_Model();
			$last_order = new Order_Model();
			
			$view = new View('order/create');
			$view->products = $this->db->query('SELECT * FROM products WHERE id in ('.$this->cart['ids'].')');
			$view->userinfo = new Customer_Model(cookie::get('userid'));
			$view->cart = $this->cart;
			$view->type = $type;
			$view->discount = $discount[$type];
			$view->nanhai = Config::item('bookstore.nanhai');
			$view->countries = $model->where('id', $view->nanhai['country_id'])->find_all();
			
			$view->last_order = $last_order->where('status', 1)
								->where('customer_id', cookie::get('userid'))
								->orderby('updated_at', 'desc')
								->limit(1)->find();
								
			$view->shipping_zones = $this->db->query('SELECT * FROM zones WHERE country_id='.($view->last_order->shipping_country_id ? $view->last_order->shipping_country_id : $view->nanhai['country_id']));
			$view->billing_zones = $this->db->query('SELECT * FROM zones WHERE country_id='.($view->last_order->billing_country_id ? $view->last_order->billing_country_id : $view->nanhai['country_id']));
			
			$ResCode = '';
			
			if($view->last_order->shipping_country_id)
			{/*
				$ResCode = myfuns::get_ups_shipping_fare(
					$view->last_order->shipping_zip_code, 
					$view->last_order->shipping_city, 
					$view->last_order->shipping_country_id, 
					'GND', 
					$this->cart['items_weight']);*/
			}
			
			$view->shipping_fare = is_numeric($ResCode) ? $ResCode : '';
						
			$this->template->content =  $view->render();
		}
		else
		{
			url::redirect('cart', 301);
		}
	}
	
	public function save($type)
	{
		if(isset($_POST['genorder']) and count($this->cart['items']) > 0)
		{
			$nanhai = Config::item('bookstore.nanhai');
			$service_type = Config::item('ups.service_type');
			
			$userinfo = new Customer_Model(cookie::get('userid'));
			$shipping_country = new Country_Model($_POST['shipping_country_id']);
			$shipping_zone = new Zone_Model($_POST['shipping_zone_id']);
			$billing_country = new Country_Model($_POST['billing_country_id']);
			$billing_zone = new Zone_Model($_POST['billing_zone_id']);
			
			$order = new Order_Model();
			
			if($type=='bookstore' or $type=='school')
			{
				$order->customer_name = $_POST['customer_name'];
				$order->customer_po_number = $_POST['customer_po_number'];
				
				$userinfo->organization = $_POST['customer_name'];
				$userinfo->po_number = $_POST['customer_po_number'];
			}
			
			if($type=='bookstore')
			{
				$order->customer_resale_permit_no = $_POST['customer_resale_permit_no'];
				$userinfo->resale_permit_no = $_POST['customer_resale_permit_no'];
			}
			
			$userinfo->type = $type;
			$userinfo->discount = $_POST['customer_discount'];
			
			if ( empty($userinfo->phone) )
				$userinfo->phone = $_POST['telephone'];
				
			if ( empty($userinfo->fax) )
				$userinfo->fax = $_POST['fax'];
			
			$userinfo->save();
						
			$order->customer_type = $type;
			$order->customer_discount = $_POST['customer_discount'];
			$order->customer_id = $userinfo->id;
			$order->firstname = $userinfo->firstname;
			$order->lastname = $userinfo->lastname;
			$order->telephone = $_POST['telephone'];
			$order->fax = $_POST['fax'];
			$order->email = $_POST['email'];
			
			$order->shipping_firstname = $_POST['firstname'];
			$order->shipping_lastname = $_POST['lastname'];
			$order->shipping_country_id = $shipping_country->id;
			$order->shipping_country = $shipping_country->name;
			$order->shipping_zone_id = $shipping_zone->id;
			$order->shipping_zone = $shipping_zone->name;
			$order->shipping_city = $_POST['shipping_city'];
			$order->shipping_zip_code = $_POST['shipping_zip_code'];
			$order->shipping_address_1 = $_POST['shipping_address_1'];
			$order->shipping_address_2 = $_POST['shipping_address_2'];
			$order->shipping_method = $service_type[$_POST['selService']];
			
			$order->billing_country_id = $billing_country->id;
			$order->billing_country = $billing_country->name;
			$order->billing_zone_id = $billing_zone->id;
			$order->billing_zone = $billing_zone->name;
			$order->billing_city = $_POST['billing_city'];
			$order->billing_zip_code = $_POST['billing_zip_code'];
			$order->billing_address_1 = $_POST['billing_address_1'];
			$order->billing_address_2 = $_POST['billing_address_2'];
			
			$order->ups_address_type = $_POST['selResidential'];
			$order->ups_packaging = $_POST['selPackaging'];
			$order->ups_service_type = $_POST['selService'];
			$order->ups_rate = $_POST['selRate'];
			
			$order->shipping_weight = $this->cart['items_weight'];
			$order->shipping_fare = $_POST['shipping_fare'];	
			
			$order->payment_type = $_POST['payment_type'];
					
			$order->amount = $this->cart['items_total'];
			
			if($type != 'bookstore' and $order->shipping_zone_id == $nanhai['zone_id'])
			{
				$order->sales_tax = Config::item('bookstore.sales_tax')*$order->amount*(1-$order->customer_discount);
			}
			
			$order->total = $order->amount*(1-$order->customer_discount)+$order->sales_tax+$order->shipping_fare;
			$order->ip = myfuns::getip();
			$order->created_at = date('Y-m-d H:i:s');
			
			$order->save(); // 保存订单
			
			$title = 'title_'.$this->lang;
			
			$products = $this->db->query('SELECT * FROM products WHERE id in ('.$this->cart['ids'].')');
			
			foreach($products as $product)
			{
				if ($this->cart['items'][$product->id]['quantities'] > $this->cart['items'][$product->id]['stock'])
					continue;
				
				$item = new Order_Item_Model();
				
				$item->product_id = $product->id;
				$item->product_name = $product->$title;
				$item->product_price = $product->price;
				$item->product_quantity = $this->cart['items'][$product->id]['quantities'];
				$item->product_subtotal = $product->price * $this->cart['items'][$product->id]['quantities'];
				$item->order_id = $order->id;
				
				$item->save();
			}
			
			$this->session->del('cart');
			
			url::redirect('order/confirm/'.$order->id, 301);
		}
		else
		{	
			url::redirect('cart', 301);
		}			
	}
	
	public function confirm($order_id)
	{
		$order = new Order_Model($order_id);
			
		$view = new View('order/confirm');
		$view->order = $order;
		$view->products = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
		$view->shipping_country = new Country_Model($order->shipping_country_id);
		$view->billing_country = new Country_Model($order->billing_country_id);
		$view->userinfo = new Customer_Model(cookie::get('userid'));
		$view->shipping_zone = new Zone_Model($order->shipping_zone_id);
		$view->billing_zone = new Zone_Model($order->billing_zone_id);
		$view->nanhai = Config::item('bookstore.nanhai');
		
		$this->template->content =  $view->render();
	}
	
	public function flagconfirm($order_id)
	{
		$config = config::item('email.options');
		$order = new Order_Model($order_id);
		
		if($order->payment_type == 'Paypal')
		{
			$view = new View('order/customer_service_email');
			$view->order = $order;
			$view->items = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
			
			$from = $config['username'];   
			$subject = 'Order #'.$order->id.' ('.$order->updated_at.')';   
			$message = $view->render(); 
			email::send(config::item('bookstore.order_email'), $from, $subject, $message, true);
			
			$order->flag_confirm = 1;
			$order->status = 1;
			$order->save();
		
			url::redirect('order/payment/'.$order_id, 301);
		}
		else
		{
			$view = new View('order/customer_email');
			$view->order = $order;
			$view->items = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
			
			$from = $config['username'];   
			$subject = 'NanHai.com: order #'.$order->id.' ('.$order->updated_at.')';   
			$message = $view->render(); 
			 
			if(email::send($order->email, $from, $subject, $message, true))
			{
				$order->flag_customer_email = 1;
			}
			
			if(email::send(config::item('bookstore.order_email'), $from, $subject, $message, true))
			{
				$order->flag_service_email = 1;
			} 
			
			$order->flag_confirm = 1;
			$order->status = 1;
			$order->save();
			
			url::redirect('order/view/'.$order_id, 301);
		}
		
		exit;
	}
	
	public function modify($order_id)
	{
		$order = new Order_Model($order_id);
			
		$view = new View('order/modify');
		$view->order = $order;
		$view->products = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
		$view->shipping_zones = Database::instance()->query('SELECT * FROM zones WHERE country_id='.$order->shipping_country_id);
		$view->billing_zones = Database::instance()->query('SELECT * FROM zones WHERE country_id='.$order->billing_country_id);
		
		$nanhai = Config::item('bookstore.nanhai');
		
		$view->countries = $this->db->query('SELECT * FROM countries WHERE id='.$nanhai['country_id']);
		
		$this->template->content =  $view->render();
	}
	
	public function update($type, $order_id)
	{
		$nanhai = Config::item('bookstore.nanhai');
		$service_type = Config::item('ups.service_type');
		
		$userinfo = new Customer_Model(cookie::get('userid'));
		$shipping_country = new Country_Model($_POST['shipping_country_id']);
		$shipping_zone = new Zone_Model($_POST['shipping_zone_id']);
		$billing_country = new Country_Model($_POST['billing_country_id']);
		$billing_zone = new Zone_Model($_POST['billing_zone_id']);
		
		$order = new Order_Model($order_id);
		
		if($type=='bookstore' or $type=='school')
		{
			$order->customer_name = $_POST['customer_name'];
			$order->customer_po_number = $_POST['customer_po_number'];
			
			$userinfo->organization = $_POST['customer_name'];
			$userinfo->po_number = $_POST['customer_po_number'];
		}
		
		if($type=='bookstore')
		{
			$order->customer_resale_permit_no = $_POST['customer_resale_permit_no'];
			$userinfo->resale_permit_no = $_POST['customer_resale_permit_no'];
		}
		
		$userinfo->type = $type;
		$userinfo->discount = $_POST['customer_discount'];
		
		if ( empty($userinfo->telephone) )
			$userinfo->telephone = $_POST['telephone'];
			
		if ( empty($userinfo->fax) )
			$userinfo->fax = $_POST['fax'];
		
		$userinfo->save();
					
		$order->customer_type = $type;
		$order->customer_discount = $_POST['customer_discount'];
		
		$order->firstname = $_POST['firstname'];
		$order->lastname = $_POST['lastname'];
		$order->telephone = $_POST['telephone'];
		$order->fax = $_POST['fax'];
		$order->email = $_POST['email'];
		
		$order->shipping_firstname = $_POST['firstname'];
		$order->shipping_lastname = $_POST['lastname'];
		$order->shipping_country_id = $shipping_country->id;
		$order->shipping_country = $shipping_country->name;
		$order->shipping_zone_id = $shipping_zone->id;
		$order->shipping_zone = $shipping_zone->name;
		$order->shipping_city = $_POST['shipping_city'];
		$order->shipping_zip_code = $_POST['shipping_zip_code'];
		$order->shipping_address_1 = $_POST['shipping_address_1'];
		$order->shipping_address_2 = $_POST['shipping_address_2'];
		$order->shipping_method = $service_type[$_POST['selService']];
		
		$order->billing_country_id = $billing_country->id;
		$order->billing_country = $billing_country->name;
		$order->billing_zone_id = $billing_zone->id;
		$order->billing_zone = $billing_zone->name;
		$order->billing_city = $_POST['billing_city'];
		$order->billing_zip_code = $_POST['billing_zip_code'];
		$order->billing_address_1 = $_POST['billing_address_1'];
		$order->billing_address_2 = $_POST['billing_address_2'];
		
		$order->ups_address_type = $_POST['selResidential'];
		$order->ups_packaging = $_POST['selPackaging'];
		$order->ups_service_type = $_POST['selService'];
		$order->ups_rate = $_POST['selRate'];
		
		$order->shipping_fare = $_POST['shipping_fare'];
		$order->payment_type = $_POST['payment_type'];
		
		if($type != 'bookstore' and $order->shipping_zone_id == $nanhai['zone_id'])
		{
			$order->sales_tax = Config::item('bookstore.sales_tax')*$order->amount*(1-$order->customer_discount);
		}
		
		$order->total = $order->amount*(1-$order->customer_discount)+$order->sales_tax+$order->shipping_fare;
		$order->ip = myfuns::getip();
		
		$order->save(); // 保存订单
		
		url::redirect('order/confirm/'.$order->id, 301);
	}
		
	public function view($order_id)
	{
		$view = new View('order/view');
		$view->order = new Order_Model($order_id);
		$view->products = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
		$this->template->content = $view->render();
	}
	
	public function payment($order_id)
	{
		$order = new Order_Model($order_id);
		
		require_once Kohana::find_file('vendors','paypal');
		
		$p = new paypal(false); 

		$this_script = url::base();
		
		//$p->add_field('business', 'hs0714_1215608929_biz@163.com');
		$p->add_field('business', 'mei@nanhai.com');
		$p->add_field('return', $this_script.'payment/success/'.$order->id);
		$p->add_field('cancel_return', $this_script.'payment/cancel/'.$order->id);
		$p->add_field('notify_url', $this_script.'payment/notify');
		$p->add_field('item_name', 'Order #'.$order_id);
		$p->add_field('amount', $order->total);
		//sean xu
		$p->add_field('cbt', 'Click here to complete order');	
	
		$p->submit_paypal_post(); // submit the fields to paypal
		//$p->dump_fields();
		exit;
	}
}
